package services;

import entities.ApplicationConfig;
import entities.ApplicationTemplate;
import entities.Article;
import entities.ArticleSearch;
import entities.Category;
import entities.User;
import forms.ArticleForm;
import forms.CaptchaForm;
import helpers.GeneralHelper;
import helpers.IdUniqueHelper;
import helpers.NumberHelper;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import javax.cache.Cache;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.ArticleModel;
import search.ArticleSearchEngine;
import systems.Recently;
import systems.RecentlyTag;

public class SubmitArticleService extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		response.setContentType("text/html");
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		ApplicationTemplate appTemplate = (ApplicationTemplate) request.getAttribute("sysTemplate");
		
		if (appTemplate == null) {
			response.getWriter().println("Please enter template");
			return ;
		}
		
		Cache memCache = GeneralHelper.getCache();
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = new Article();
		article.setLanguage(language);
		
		TreeMap form = ArticleForm.checkValid(request, article);
		TreeMap<String, String> check = (TreeMap<String, String>) form.get("checkValid");
		article = (Article) form.get("article");
		
		if (check.size() == 0) {
			//Check submitStatus config
			article.setStatus(1);
			
			article.setId(IdUniqueHelper.getId());
			article.setRate(NumberHelper.getRandomNumberFrom(2, 5));
			article.setAuthKey(IdUniqueHelper.getId());
			articleModel.insert(appConfig.getApplicationId(), article);
			
			//Set search article
			ArticleSearch articleSearch = ArticleSearch.convert(article);
			ArticleSearchEngine.update(articleSearch);
			
			//Update tag
			RecentlyTag.insert(appConfig.getApplicationId(), article.getKeywords());
			
			//Update recently Cache
			if (article.getStatus() == 1) {
				Recently.update(appConfig.getApplicationId(), article);
			}
			
			response.getWriter().println("Submit article success with id " + article.getId());
		} else {
			for (Map.Entry<String,String> entry : check.entrySet()) {
		        String value = entry.getValue();
		        String key = entry.getKey();
		        
		        response.getWriter().println(value);
		   }
		}
		
	}
}
